# 2023年秋季学期《高等程序设计语言》期末考核项目：学生信息管理系统



# 导入必需模块
import os
import os.path

os.chdir('D:\\')

if not os.path.exists('newdir'):
    os.mkdir('newdir')

os.chdir('D:\\newdir')

# 编写目录子函数
def menm(): 
    print('\n\n','学生信息管理系统'.center(60,'='),'\n')
    print('目录'.center(60),'\n')
    print('\t\t\t1、录入学生信息')
    print('\t\t\t2、查找学生信息')
    print('\t\t\t3、删除学生信息')
    print('\t\t\t4、修改学生信息')
    print('\t\t\t5、排序')
    print('\t\t\t6、统计学生总人数')
    print('\t\t\t7、显示所有学生信息')
    print('\t\t\t8、打开学生信息文件')
    print('\t\t\t9、退出系统')
    print('====================================================================')


# 编写主函数
def main():
    if not os.path.exists('stuinfomgr.txt'):
        with open('stuinfomgr.txt','w+',encoding='UTF-8') as fp:
            fp.write('学号\t\t姓名\t\t性别\t\t数学\t\t物理\t\tPython\t\t平均成绩\n')

    # 功能模块
    while True:
        menm()
        select = int(input('\n请选择功能:'))

        if select == 1:
            while True:
                stu_id=input('\t请输入学生学号:')
                stu_name=input('\t请输入学生姓名:')
                stu_gender=input('\t请输入学生性别:')
                stu_score_math = int(input('\t请输入数学成绩:'))
                stu_score_phy = int(input('\t请输入物理成绩:'))
                stu_score_pyth = int(input('\t请输入python成绩:'))
                stu_ave=(stu_score_math+stu_score_phy+stu_score_pyth)/3
                
                with open('stuinfomgr.txt','a+') as fp:
                    fp.writelines(['\n',stu_id,'\t\t',stu_name,'\t\t',stu_gender,'\t\t',str(stu_score_math),'\t\t',str(stu_score_phy),'\t\t',str(stu_score_pyth),'\t\t',str( stu_ave)])
                selec= input('\n是否继续输入学生信息? y/n: ')
                if selec != "y":
                    break


        elif select == 2:
            while True:
                char = input("\n请输入待查询的学生的学号或姓名:")
                with open("stuinfomgr.txt", "r", encoding="UTF-8") as fp:
                    lst = fp.readlines()

                for item in lst:
                    if char in item[:9]:
                        lst_info = item.split(sep="\t\t")
                        print("\n姓名:",lst_info[1],"\t学号:",lst_info[0],"\t性别:",lst_info[2],)
                        print("数学成绩：", lst_info[3], end="\t")
                        print("物理成绩：", lst_info[4], end="\t")
                        print("Python成绩:", lst_info[5])
                        print("平均成绩：", lst_info[6], "\n")
                        break
                else:
                    print("未查到学生信息")
                
                selec = input("是否继续查找学生信息? y/n:")
                if selec != "y":
                    break
        elif select == 3:
            while True:
                char = input("\n请输入删除的学生学号或姓名:")
                with open("stuinfomgr.txt", "r", encoding="UTF-8") as fp:
                    lst = fp.readlines()

                k = 0
                for item in lst[2:]:
                    if char in item:
                        break
                    k += 1
                else:
                    print("未查到学生信息")
                    break
                del lst[k + 2]

                with open("stuinfomgr.txt", "w", encoding="UTF-8") as fp:
                    fp.writelines(lst)
                selec = input("是否继续删除学生信息? y/n:")
                if selec != "y":
                    break

        elif select == 4:
            while True:
                with open("stuinfomgr.txt", "r", encoding="UTF-8") as fp:
                    lst = fp.readlines()
                lst_of_dic = []
                if len(lst) >= 2:
                    for item in lst[2:]:
                        elem = item.split(sep="\t\t")
                        dic = {"学号": elem[0], "姓名": elem[1],"性别": elem[2],"数学": elem[3], "物理": elem[4], "Python": elem[5],}
                        lst_of_dic.append(dic)
                else:
                    print("无学生信息,请先录入\n\n")
                    break
                k = 0
                char = input("\n请输入待修改的学生学号或姓名:")
                for item in lst_of_dic:
                    if char == item["姓名"] or char == item["学号"]:
                        break
                    k += 1
                else:
                    print("未查到学生信息")
                    break

                while True:
                    scro = input("\n请输入待修改的项(学号/姓名/性别/数学/物理/Python):")
                    if scro in "请输入待修改的项(学号/姓名/性别/数学/物理/Python)":
                        val = input("\n请输入修改后的内容:")
                        lst_of_dic[k][scro] = val
                    else:
                        print("关键字不存在")
                        break

                stu_ave = (int(lst_of_dic[k]['数学'])+int(lst_of_dic[k]['物理'])+int(lst_of_dic[k]['Python']))
                lst_ch = ''.join([lst_of_dic[k]['学号'],'\t\t',lst_of_dic[k]['姓名'],'\t\t'])
                lst_ch1 = ''.join([lst_of_dic[k]['学号'],'\t\t',lst_of_dic[k]['姓名'],'\t\t'])

                if k+1 < len(lst_of_dic):
                            lst[k+2] = lst_ch
                else:
                            
                        lst[k+2] = lst_ch1
                        with open('stuinfomgr.txt','w',encoding='UTF-8') as fp:
                            fp.writelines(lst)
                        
                selec = input('是否继续修改下一个学生的信息?y/n:')
                if selec != 'y':
                    break

        
        elif select == 5:
            
            with open('stuinfomgr.txt','r',encoding='UTF-8') as fp:
                lst=fp.readlines()      

            
            lst_of_dic=[]     
            if len (lst) >=2:  
                for item in lst[2:]:    
                    elem=item.split(sep='\t\t')
                    av = elem[6].split(sep='\n')
                    dic = {'学号':elem[0],'姓名':elem[1],'性别':elem[2],'数学':elem[3],'物理':elem[4],'Python':elem[5],"平均成绩": str(av)}
                    lst_of_dic.append(dic)
                else:
                    print('无学生信息，请先录入\n\n')
                    break     
                            
            choice = input ('请输入排列名目（学号/数学/物理/Python/平均分）：')
            if choice in '学号/数学/物理/Python/平均分':
                sen_or_desen = input('请输入按升序排序还是降序排列（升/降）:')
                if sen_or_desen =='升':
                    for item1 in range(len(lst_of_dic)-1):
                        for item2 in range(item1,len(lst_of_dic)):
                            if int(lst_of_dic[item1][choice]) >= int(lst_of_dic[item2][choice]):
                                lst_of_dic[item1],lst_of_dic[item2]=lst_of_dic[item2],lst_of_dic[item1]
                elif sen_or_desen == '降':
                    for item1 in range(len(lst_of_dic)-1): 
                        for item2 in range(item2,len(lst_of_dic)):
                            if int(lst_of_dic[item1][choice]) <= int(lst_of_dic[item2][choice]):
                                lst_of_dic[item1],lst_of_dic[item2]=lst_of_dic[item2],lst_of_dic[item1]
                else:
                    print('关键字不存在')

            
            lst =[]
            N =len(lst_of_dic)

            for item in range(N):
                stu_ave =(int(lst_of_dic[item]['数学'])+int(lst_of_dic[item]['物理'])+int(lst_of_dic[item]['Python']))
                stg = ''.join(['\n',lst_of_dic[item]['学号'],'\t\t',lst_of_dic[item]['姓名'],'\t',lst_of_dic[item]['性别']])
                lst.append(stg)

            with open('stuinfomgr.txt','w+',encording="UTF-8") as fp:
                fp.write('学号\t\t姓名\t\t性别\t\t数学\t\t物理\t\tPython\t\t平均分\n')

            with open('stuinfomgr.txt','a+',encording="UTF-8") as fp:
                    fp.writelines(lst)    

        
        elif select == 6:
            with open("stuinfomgr.txt", "r", encoding="UTF-8") as fp:
                lst = fp.readlines()
            print("\n共有学生", len(lst) - 2, "人\n")

        
        elif select == 7:
            
            try:
                with open('stuinfomgr.txt','r',encoding='UTF-8')as fp:
                    lst=fp.readlines()

                lst_of_dic=[]
                if len(lst)>=2:
                    for item in lst[2:]:
                        elem=item.split(sep='\t\t')
                        dic={'学号':elem[0],'姓名':elem[1],'性别':elem[2],'数学':elem[3],'物理':elem[4],'Python':elem[5]}
                        lst_of_dic.append(dic)
                else:
                    print('无学生信息,请先录入\n\n')

                format_title = "{:<6}\t{:<6}\t{:<6}\t{:<6}\t{:<6}\t{:<6}\t{:<6}"
                

                print(format_title.format("学号", "姓名", "性别", "数学", "物理", "Python", "平均分"))

                for item in lst_of_dic:
                    stu_ave = (int(item["数学"]) + int(item["物理"]) + int(item["Python"])) / 3
                    stu_ave = "{:.2f}".format(stu_ave)
                    print(
                        format_title.format(
                            item.get("学号"),
                            item.get("姓名"),
                            item.get("性别"),
                            item.get("数学"),
                            item.get("物理"),
                            item.get("Python"),
                            stu_ave,))
            except:
                print("学生信息文件不存在")

        
        elif select == 8:
            path = os.getcwd()
            filename = 'stuinfomgr.txt'
            try:
                os.startfile(os.path.join(path,filename))
            except:
                print('学生信息文件不存在')

        elif select == 9:
            print('\n\n程序已终止\n\n')
            os.remove('D:\\newdir\\stuinfomgr.txt')
            os.chdir('D:\\')
            os.rmdir('newdir')
            break
        else:
            print('\n功能不存在,请重新输入\n')

if __name__ == '__main__':
        main()
